package dataCenter.thread;

import java.util.logging.Level;
import java.util.logging.Logger;

import net.socket.SocketConnection;
import net.socket.packet.SocketReceivablePacket;
import net.socket.packet.SocketSendablePacket;

import com.google.protobuf.InvalidProtocolBufferException;

import data.DataController;
import data.packetBuffer.users.UserBuffer.BufferUser;
import data.packetBuffer.users.UserRolesBuffer.BufferUserRoles;
import data.packetCode.UserPacketCode;

public class ConnectionReceivableThread implements Runnable
{
	private SocketConnection socketConnection;
	private SocketReceivablePacket socketReceivablePacket;

	public ConnectionReceivableThread(SocketConnection socketConnection, SocketReceivablePacket socketReceivablePacket)
	{
		this.socketConnection=socketConnection;
		this.socketReceivablePacket=socketReceivablePacket;
	}

	@Override
	public void run()
	{
		readReceivablePacket();
	}

	private void readReceivablePacket()
	{
		switch(socketReceivablePacket.getPacketCode())
		{
		case UserPacketCode.USER_DATA:
			try
			{
				BufferUser bufferUser = BufferUser.parseFrom(socketReceivablePacket.getBytes());
				BufferUser bufferUserInfo = DataController.dataSql().userDataSql().getUserInfo(bufferUser.getServerID(), bufferUser.getUserAccount());
				byte[] bytes=bufferUserInfo.toByteArray();
				SocketSendablePacket socketSendablePacket = new SocketSendablePacket(bytes.length, UserPacketCode.USER_DATA, socketReceivablePacket.getCommandID());
				socketSendablePacket.put(bytes);
				socketConnection.sendPacket(socketSendablePacket);
			}
			catch (InvalidProtocolBufferException e)
			{
				Logger.getLogger(ConnectionReceivableThread.class.getName()).log(Level.SEVERE, null, e);
			}
			break;
		case UserPacketCode.USER_ROLES_DATA:
			try
			{
				BufferUser bufferUser = BufferUser.parseFrom(socketReceivablePacket.getBytes());
				BufferUserRoles bufferUserRoles = DataController.dataSql().userDataSql().getUserRolesInfo(bufferUser.getId());
				byte[] bytes=bufferUserRoles.toByteArray();
				SocketSendablePacket socketSendablePacket = new SocketSendablePacket(bytes.length, UserPacketCode.USER_ROLES_DATA, socketReceivablePacket.getCommandID());
				socketSendablePacket.put(bytes);
				socketConnection.sendPacket(socketSendablePacket);
			} 
			catch (InvalidProtocolBufferException e)
			{
				Logger.getLogger(ConnectionReceivableThread.class.getName()).log(Level.SEVERE, null, e);
			}
			break;
		}
	}
}
